import { Input, type InputProps } from 'ant-design-vue'
import { defineComponent, onMounted, ref, nextTick } from 'vue'
import type { PropType } from 'vue'
import type { JsonSchema } from '../types'
import { getProp } from '@/components/cms/utils'
import { formState } from '../mixins/useState'

export default defineComponent({
  inheritAttrs: true,
  emits: ['valueChange'],
  props: {
    schema: {
      type: Object as PropType<JsonSchema>,
      default: () => ({})
    },
    model: {
      type: Object as PropType<any>
    }
  },
  setup(props, ctx) {
    const attrs = { ...props.schema.props } as InputProps
    const text = ref('')
    const handleChange = () => {
      if (!props.schema.field) {
        console.warn('字段没有传递')
        return
      }
      const value = {
        path: props.schema.field,
        value: text.value
      }
      ctx.emit('valueChange', value)
    }
    onMounted(() => {
      nextTick(() => {
        const value = getProp(formState.model, props.schema.field as string).value as string
        text.value = value
      })
    })
    return () => <Input {...attrs} v-model={[text.value, 'value']} onChange={() => handleChange()} />
  }
})
